/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.category.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.category.param.*;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.category.entity.TblCategory;
import vip.xiaonuo.biz.modular.category.mapper.TblCategoryMapper;
import vip.xiaonuo.biz.modular.category.service.TblCategoryService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 题库分类表Service接口实现类
 *
 * @author 范庆奥
 * @date 2025/02/26 17:35
 **/
@Service
public class TblCategoryServiceImpl extends MPJBaseServiceImpl<TblCategoryMapper, TblCategory> implements TblCategoryService {


    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Override
    public Page<TblCategory> page(TblCategoryPageParam tblCategoryPageParam) {
        QueryWrapper<TblCategory> queryWrapper = new QueryWrapper<TblCategory>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(tblCategoryPageParam.getType())){
            queryWrapper.lambda().like(TblCategory::getType, tblCategoryPageParam.getType());
        }
        if (ObjectUtil.isNotEmpty(tblCategoryPageParam.getName())) {
            queryWrapper.lambda().like(TblCategory::getName, tblCategoryPageParam.getName());
        }
        if (ObjectUtil.isNotEmpty(tblCategoryPageParam.getParentId())) {
            queryWrapper.lambda().eq(TblCategory::getParentId, tblCategoryPageParam.getParentId());
        }
        if (ObjectUtil.isAllNotEmpty(tblCategoryPageParam.getSortField(), tblCategoryPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(tblCategoryPageParam.getSortOrder());
            queryWrapper.orderBy(true, tblCategoryPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(tblCategoryPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(TblCategory::getSortCode);
        }
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)){
            queryWrapper.lambda().in(TblCategory::getOrgId,loginUserDataScope);
        }else {
            queryWrapper.lambda().eq(TblCategory::getCreateUser, StpUtil.getLoginIdAsString());
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TblCategoryAddParam tblCategoryAddParam) {
        TblCategory tblCategory = BeanUtil.toBean(tblCategoryAddParam, TblCategory.class);
        tblCategory.setOrgId(StpLoginUserUtil.getLoginUser().getOrgId());
        this.save(tblCategory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TblCategoryEditParam tblCategoryEditParam) {
        TblCategory tblCategory = this.queryEntity(tblCategoryEditParam.getId());
        BeanUtil.copyProperties(tblCategoryEditParam, tblCategory);
        this.updateById(tblCategory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TblCategoryIdParam> tblCategoryIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(tblCategoryIdParamList, TblCategoryIdParam::getId));
    }

    @Override
    public TblCategory detail(TblCategoryIdParam tblCategoryIdParam) {
        return this.queryEntity(tblCategoryIdParam.getId());
    }

    @Override
    public TblCategory queryEntity(String id) {
        TblCategory tblCategory = this.getById(id);
        if (ObjectUtil.isEmpty(tblCategory)) {
            throw new CommonException("题库分类表不存在，id值为：{}", id);
        }
        return tblCategory;
    }

    @Override
    public List<Tree<String>> categoryTreeSelector(TblCategoryTreeParam tblCategoryTreeParam) {
        QueryWrapper<TblCategory> queryWrapper = new QueryWrapper<TblCategory>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(tblCategoryTreeParam.getType())) {
            queryWrapper.lambda().like(TblCategory::getType, tblCategoryTreeParam.getType());
        }
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)){
            queryWrapper.lambda().in(TblCategory::getOrgId,loginUserDataScope);
        }else {
            queryWrapper.lambda().eq(TblCategory::getCreateUser, StpUtil.getLoginIdAsString());
        }
        queryWrapper.lambda().orderByAsc(TblCategory::getSortCode);
        List<TblCategory> sysOrgList = this.list(queryWrapper);
        List<TreeNode<String>> treeNodeList = sysOrgList.stream().map(sysOrg ->
                        new TreeNode<>(sysOrg.getId(), sysOrg.getParentId(), sysOrg.getName(), sysOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public List<String> getCategoryIdsByParentId(String parentId) {
        QueryWrapper<TblCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TblCategory::getParentId, parentId).select(TblCategory::getId);
        List<String> categoryList = this.baseMapper.selectObjs(queryWrapper);
        categoryList.add(parentId);
        return categoryList;
    }


}
